/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 TCPAcceptor.hpp. Created on: 20.08.2009 15:57:58
 */

#ifndef TCPACCEPTOR_HPP_
#define TCPACCEPTOR_HPP_

#include "TCPSharedResources.hpp"
#include "smartobjects/SmartObjectsDefs.hpp"
#include "smartobjects/network/IAcceptor.hpp"
#include "SocketURI.hpp"

namespace smartobjects {

class TCPAcceptor : public IAcceptor {
public:
	SO_DLLPRFX TCPAcceptor(TCPSharedResources::SharedPtr);
	SO_DLLPRFX virtual ~TCPAcceptor();

	SO_DLLPRFX virtual void start(void) throw (const IOException&);
	SO_DLLPRFX virtual void stop(void) ;
	SO_DLLPRFX virtual bool isOpen(void) ;
	SO_DLLPRFX virtual void setEndpointURI(URI*) throw (const IOException&) ;
	SO_DLLPRFX virtual URI* getEndpointURI(void) ;
	SO_DLLPRFX virtual void addListener(IAcceptorListener*) ;
	SO_DLLPRFX virtual void delListener(IAcceptorListener*) ;

protected:
	SO_DLLPRFX void prepareAcceptorSocket() throw (const IOException&) ;
	SO_DLLPRFX void startAcceptorSocketListener() throw (const IOException&) ;
	SO_DLLPRFX void onAccepted();
	SO_DLLPRFX class TCPAcceptorConnection*
					createAcceptorConnection(
							smartobjects::sockets::Socket hClientSocket,
							smartobjects::sockets::SocketAddr& oClientAddr);
	SO_DLLPRFX void resetAllAcceptorConnections();

	SO_DLLPRFX virtual void fireOnAccepted(IConnection* poConnection);
	SO_DLLPRFX void processingPostActionAcceptorListeners();
	SO_DLLPRFX void removeConnection(TCPAcceptorConnection* poConnection);

	friend class TCPAcceptorConnection;
protected:

	static const char* ACCEPTOR_MULTIPLEXER_GROUP_NAME;

	TCPSharedResources::SharedPtr m_poSharedResources;
	smartobjects::sockets::SocketMultiplexer::SharedPtr m_poMultiplexer;

	typedef std::list<IAcceptorListener*> AcceptorListeners;
	AcceptorListeners m_aAcceptorListeners;
	PostActionListenersContainer<IAcceptorListener> m_oPALAcceptorListeners;
	boost::recursive_mutex m_mxAcceptorListeners;

	smartobjects::sockets::SocketURI* m_poSocketURI;

	boost::recursive_mutex m_mxAcceptorSocketLock;
	smartobjects::sockets::Socket m_hAcceptorSocket;

	boost::recursive_mutex m_mxAsyncEvent;

	typedef std::set < TCPAcceptorConnection* > AcceptorConnections;
	AcceptorConnections m_aAcceptorConnections;
	boost::recursive_mutex m_mxAcceptorConnections;

	bool m_bStoppedState;

};

}

#endif /* TCPACCEPTOR_HPP_ */
